﻿using Com.Lancetinc.Evs.Helpers;
using System;
using System.IO;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Com.Lancetinc.Evs.Resources
{
    public static class ResourceHelper
    {
        private static readonly string ImageFileDir = Path.Combine(DirUtil.ExeDirectory, "Resources");

        /// <summary>
        /// 取得图片资源
        /// 优先从外部文件中取得，如果取不到则从打包的资源取
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static BitmapImage GetImage(string key)
        {
            if (WpfHelper.IsInDesignMode) return null;

            var fileName = FixFileName(key);
            var file = Path.Combine(ImageFileDir, fileName);
            if (File.Exists(file))
                return GetImageFromFile(file);

            return GetImageFromAssets(fileName);
        }

        public static BitmapImage GetImageFromFile(string file, bool useCache = true)
        {
            // 注意：直接 new BitmapImage(new Uri(file)) 会锁住文件
            var img = new BitmapImage();
            img.BeginInit();
            img.CacheOption = BitmapCacheOption.OnLoad;
            if (!useCache)
            {
                img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            }
            img.UriSource = new Uri(file);
            img.EndInit();
            return img;
        }

        public static BitmapImage GetImageFromAssets(string key)
        {
            var imageUri = $"pack://application:,,,/Resources/{key}";
            return new BitmapImage(new Uri(imageUri));
        }

        private static Size? _cameraLogoSize;
        public static Size CameraLogoSize()
        {
            if (_cameraLogoSize.HasValue)
                return _cameraLogoSize.Value;
            var img = GetImage("logo");
            _cameraLogoSize = new Size(img.PixelWidth, img.PixelHeight);
            return _cameraLogoSize.Value;
        }

        private static string FixFileName(string key)
        {
            var fileName = key;
            if (!fileName.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
                fileName += ".png";

            return fileName;
        }
    }

    [MarkupExtensionReturnType(typeof(ImageSource))]
    public class ImageResourceExtension : MarkupExtension
    {
        [ConstructorArgument("source")]
        public string Source { get; set; }

        public ImageResourceExtension()
        {
        }

        public ImageResourceExtension(string source)
        {
            this.Source = source ?? throw new ArgumentNullException("source");
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (Source == null)
            {
                return null;
            }

            return ResourceHelper.GetImage(Source);
        }
    }
}